<template>
  <div>
    <a-modal :visible="visible" :title="type == 'add' ? '创建其他出库单' : '编辑其他出库单'" @before-open="open" :on-before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" :width="1200" :mask-closable="false">
      <!-- <template #title> 创建其他出库单 </template> -->
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-space direction="vertical" :size="24">
            <a-row>
              <a-col :span="10">
                <a-form-item field="warehouseCode" label="选择仓库" :rules="rules.warehouseCode">
                  <a-select @change="selHouse" :disabled="type == 'edit'" v-model="form.warehouseCode" placeholder="请选择仓库" allow-clear allow-search>
                    <a-option v-for="item of houseList" :label="item.warehouseName" :value="item.warehouseCode"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="14">
                <a-form-item field="shopId" label="店铺">
                  <a-select @change="selShop" :disabled="type == 'edit'" v-model="form.shopId" placeholder="请选择店铺" allow-clear allow-search>
                    <a-option v-for="item of shopList" :label="item.shopName" :value="item.sellerMarketId"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item field="remark" label="备注">
                  <a-input v-model="form.remark" placeholder="请输入备注"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-space>
        </a-form>
      </div>
      <div>
        <a-button size="medium" type="primary" @click="addProduct">添加出库货品</a-button>
        <span style="margin-left: 10px">已选SKU：</span><span>{{ skuKind }}</span> <span style="margin-left: 10px">出库数量：</span><span>{{ outNum }}</span>

        <a-table :pagination="false" size="mini" class="table-singe-line" style="margin-top: 10px" :data="tableList" :scroll="{ x: '100%', y: '400px' }">
          <template #columns>
            <a-table-column title="店铺" :width="100" #cell="{ record }">
              <TextLimit position="top" :val="record.shopName"></TextLimit>
            </a-table-column>
            <a-table-column title="货主" width="70" #cell="{ record }">{{ record.ownerName ? record.ownerName : '--' }} </a-table-column>
            <a-table-column title="图片" width="60">
              <template #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image height="40px" width="40px" :src="record.productImg" />
                  </template>
                </ImgPopover>
                <!-- <a-image height="40px" width="40px" :src="record.productImg" /> -->
              </template>
            </a-table-column>
            <a-table-column title="产品名称/SKU" width="120">
              <template #cell="{ record }">
                <div>
                  <TextLimit position="top" :val="record.productName"></TextLimit>
                </div>
                <div>{{ record.sku }}</div>
              </template>
            </a-table-column>
            <a-table-column title="MSKU/FNSKU" width="120">
              <template #cell="{ record }">
                <div>
                  <TextLimit position="top" :val="record.msku"></TextLimit>
                </div>
                <div>
                  <TextLimit position="top" :val="record.fnsku"></TextLimit>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="货位" width="120">
              <template #cell="{ record }">
                {{ record.locationCode }}
              </template>
            </a-table-column>
            <a-table-column title="库存属性" width="80">
              <template #cell="{ record }">
                {{ record.attribute == 'good' ? '良品' : '次品' }}
              </template>
            </a-table-column>
            <a-table-column title="可出库数量" width="100">
              <template #cell="{ record }">
                {{ record.amtAvailable ? record.amtAvailable : '0' }}
              </template>
            </a-table-column>
            <a-table-column title="出库数量" width="160">
              <template #cell="{ record, rowIndex }">
                <a-input-number style="width: 100px" :max="record.amtAvailable" hide-button v-model="record.amt" />
                <a-button size="small" class="gray-outline" style="margin-left: 5px" @click="setPro('amt', record, rowIndex)">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </template>
            </a-table-column>
            <a-table-column title="单位成本" width="120">
              <template #cell="{ record }">
                {{ record.price }}
              </template>
            </a-table-column>
            <a-table-column title="货值" width="120">
              <template #cell="{ record }">
                {{ (record.amt || 0) * record.price }}
              </template>
            </a-table-column>
            <a-table-column title="操作" width="60">
              <template #cell="{ record, rowIndex }">
                <a-button type="text" size="medium" @click="tableList.splice(rowIndex, 1)">移除</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
  <SelProduct ref="productlist" :warehouseCode="form.warehouseCode" :shopId="shopInfo.sellerMarketId" @save="saveProduct" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed, h } from 'vue'
  import { findWarehouseListByParam, findShopListByShare, createOtherOut, updateOtherOut, getOtherOutInfo } from '@/api/warehouse'
  import SelProduct from './selOuthouseProduct.vue'
  import { IconSearch } from '@arco-design/web-vue/es/icon'
  import { Message } from '@arco-design/web-vue'
  export default defineComponent({
    props: ['type', 'id'],
    components: {
      SelProduct,
    },
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const productlist = ref()
      const data: any = reactive({
        form: {
          shopId: '',
        },
        rules: {
          warehouseCode: [{ required: true, message: '请选择仓库' }],
          shopId: [{ required: true, message: '请选择店铺' }],
        },
        titleFormValue: {
          amt: '',
        },
        tableList: [],
        shopList: [],
        houseList: [],
        shopInfo: {},
      })

      const open = () => {
        getShopList()
        getWarehouseList()
        if (props.type == 'edit') getDetail()
      }

      const getDetail = async () => {
        const res = await getOtherOutInfo({ id: props.id })
        data.form = res?.data || {}
        data.tableList = res?.data?.otherOutItems || []
      }

      const handleOk = (done: any) => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            if (data.tableList.length <= 0) {
              done(true)
              return Message.error('请添加出库货品')
            }
            let params = {
              ...data.form,
              otherOutItems: [],
            }

            console.log(data.tableList, 'ppppppppppp')

            data.tableList.forEach((e: any) => {
              let obj: any = {
                amt: e.amt,
                attribute: e.attribute,
                brandId: e.brand ? e.brand.id : '',
                brandName: e.brand ? e.brand.name : '',
                cateId: e.category ? e.category.id : '',
                cateName: e.category ? e.category.name : '',
                fnsku: e.fnsku,
                locationCode: e.locationCode,
                locationId: e.locationId,
                ownerId: e.ownerId,
                ownerName: e.ownerName,
                msku: e.msku,
                price: e.avgPrice || e.price,
                inventoryId: props.type == 'add' ? e.id : e.inventoryId,
                productImg: e.productImg,
                productName: e?.skuName || '',
                productType: e?.productType || '',
                remark: '',
                sku: e?.sku || '',
                spu: e?.spu,
              }

              if (props.type == 'edit' && e.id) {
                obj.id = e.id
              }

              params.otherOutItems.push(obj)
            })

            let res: any = {}

            try {
              if (props.type == 'add') {
                res = await createOtherOut(params)
              } else {
                res = await updateOtherOut(params)
              }
              if (res.code == 'SUCCESS') {
                props.type == 'add' ? Message.success('创建成功') : Message.success('更新成功')
                emit('save')
                handleCancel()
              }
              done(true)
            } catch (error) {
              done(true)
            }
          } else {
            done(true)
          }
        })
      }
      const handleCancel = () => {
        formRef.value.clearValidate()
        data.form = {}
        data.titleFormValue.amt = ''
        data.tableList = []
        visible.value = false
      }
      // 获取店铺列表
      const getShopList = async () => {
        const res = await findShopListByShare()
        data.shopList = res?.data || []
      }
      // 获取仓库列表
      const getWarehouseList = async () => {
        const res = await findWarehouseListByParam()
        data.houseList = res?.data || []
      }
      const getColumn = (data: any) => {
        console.log(data)
      }

      const saveProduct = (arr: any) => {
        console.log(arr)

        if (data.tableList.length <= 0) {
          data.tableList = arr
        } else {
          arr.forEach((e: any) => {
            let index = data.tableList.findIndex((el: any) => el.id == e.id)
            if (index == -1) {
              data.tableList.push(e)
            }
          })
        }
      }

      const setPro = (type: string, info: any, index: number) => {
        if (!info[type]) {
          Message.error('请输入或选择相应的值')
          return
        }
        data.tableList.forEach((e: any, i: number) => {
          if (i >= index) {
            if (info[type] > e.amtAvailable) {
              e.amt = e.amtAvailable
            } else {
              e.amt = info[type]
            }
          }
        })
      }

      const addProduct = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            productlist.value.visible = true
          }
        })
      }

      const selHouse = (val: string) => {
        if (val) {
          // getSpaceList(val)
        } else {
          data.houseLocationList = []
        }
        let obj = data.houseList.find((e: any) => e.warehouseCode == val)
        data.form.warehouseName = obj.warehouseName
        data.tableList = []
      }

      const selShop = (val: string) => {
        data.shopInfo = data.shopList.find((e: any) => e.sellerMarketId == val)
        // let obj = data.shopList.find((e: any) => e.id == val)
        // data.form.shopName = obj.shopName
        data.form.sellerId = data.shopInfo.sellerId
        data.form.marketplaceId = data.shopInfo.marketplaceId
      }

      const skuKind = computed(() => {
        let skuArr: any = []
        data.tableList.forEach((e: any) => {
          let index = skuArr.findIndex((el: any) => el == e.sku || e.msku)
          if (index == -1) {
            skuArr.push(e?.sku || e?.msku)
          }
        })
        return skuArr.length
      })

      const outNum = computed(() => {
        let num = 0
        data.tableList.forEach((e: any) => {
          num += e?.amt || 0
        })
        return num
      })

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        getColumn,
        productlist,
        saveProduct,
        setPro,
        addProduct,
        skuKind,
        outNum,
        selShop,
      }
    },
  })
</script>

<style lang="less" scoped></style>
